package com.vhuomai.store.provider;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.quanyue.auto.util.KeyGenerator;
import com.quanyue.auto.util.http.Http;
import com.vhuomai.store.entity.BaseStoreConfig;
import com.vhuomai.store.exception.StoreException;

import java.io.InputStream;

/**
 * @author harris
 */
public class QiniuStoreProvider implements StoreProvider {
    
    @Override
    public String saveFile(BaseStoreConfig config, byte[] content, String ext) throws StoreException {
        return this.saveFileByName(config, content, KeyGenerator.uuid() + ext);
    }
    
    @Override
    public String saveFileByName(BaseStoreConfig config, byte[] content, String fileName) throws StoreException {
        UploadManager uploadManager = new UploadManager(new Configuration());
        Auth auth = Auth.create(config.getSecretId(), config.getSecretKey());
        String token = auth.uploadToken(config.getBucket());
        try {
            uploadManager.put(content, fileName, token);
        } catch (QiniuException e) {
            throw new StoreException("文件保存失败, " + e.error(), e);
        }
        return config.getDomainUrl() + fileName;
    }
    
    @Override
    public boolean fileExist(BaseStoreConfig config, String url) throws StoreException {
        Auth auth = Auth.create(config.getSecretId(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, new Configuration());
        String fileName = url.substring(config.getDomainUrl().length());
        try {
            FileInfo fileInfo = bucketManager.stat(config.getBucket(), fileName);
            return fileInfo != null;
        } catch (QiniuException e) {
            throw new StoreException("文件获取失败, " + e.error(), e);
        }
    }
    
    @Override
    public void remove(BaseStoreConfig config, String url) throws StoreException {
        Auth auth = Auth.create(config.getSecretId(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, new Configuration());
        String fileName = url.substring(config.getDomainUrl().length());
        try {
            bucketManager.delete(config.getBucket(), fileName);
        } catch (QiniuException e) {
            throw new StoreException("文件删除失败, " + e.error(), e);
        }
    }
    
    @Override
    public InputStream getContent(BaseStoreConfig config, String url) throws StoreException {
        return Http.get(url).execute().inputStream();
    }
}
